package com.health.viewscontrols.tjbg.fragment;

import android.graphics.Color;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;

import com.blankj.utilcode.util.TimeUtils;
import com.github.mikephil.charting.charts.LineChart;
import com.github.mikephil.charting.components.AxisBase;
import com.github.mikephil.charting.components.Description;
import com.github.mikephil.charting.components.Legend;
import com.github.mikephil.charting.components.XAxis;
import com.github.mikephil.charting.components.YAxis;
import com.github.mikephil.charting.data.Entry;
import com.github.mikephil.charting.data.LineData;
import com.github.mikephil.charting.data.LineDataSet;
import com.github.mikephil.charting.formatter.IAxisValueFormatter;
import com.github.mikephil.charting.highlight.Highlight;
import com.github.mikephil.charting.listener.OnChartValueSelectedListener;
import com.health.R;
import com.health.tablebean.SBCL_DATA;
import com.health.viewscontrols.NovaApplication;
import com.health.viewscontrols.tjbg.MyMarkerView;
import com.health.viewscontrols.tjbg.base.BaseFragment;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
 * author : xiaoxin
 * date   : 2020/12/21 11:52
 * desc   :
 * update :
 */
public class NiaoSuanFragment extends BaseFragment implements OnChartValueSelectedListener {

    //x y 轴数据 月
    private List<String> xDayData = new ArrayList<>();
    private List<String> yDayData = new ArrayList<>();

    private LineChart lineChart;
    private TextView tv_tjbg_no_data;
    String strWhere = "IDCARD = '" + NovaApplication.getUserInfo().getIDCARD() + "'";

    public static NiaoSuanFragment newInstance() {

        NiaoSuanFragment fragment = new NiaoSuanFragment();
        Bundle args = new Bundle();
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    protected int getContentViewLayoutID() {
        return R.layout.fragment_chat;
    }

    @Override
    protected void initView(View view) {
        lineChart = view.findViewById(R.id.linechart);
        tv_tjbg_no_data = view.findViewById(R.id.tv_tjbg_no_data);
    }

    @Override
    protected void initData() {

        initChartView();
        try {
            List<SBCL_DATA> list1 = NovaApplication.fdbmanger.findAllByWhere(SBCL_DATA.class,
                    strWhere + "AND CL_TYPE_NAME = '尿酸' ORDER BY CL_TIME DESC");
            if (list1 == null || list1.size() <= 0) {
                lineChart.setVisibility(View.GONE);
                tv_tjbg_no_data.setVisibility(View.VISIBLE);
                tv_tjbg_no_data.setText("暂无尿酸体检数据");
            } else {
                lineChart.setVisibility(View.VISIBLE);
                tv_tjbg_no_data.setVisibility(View.GONE);
                for (int i = 0; i < list1.size(); i++) {
                    if (i <= 6) {
                        try {
                            xDayData.add(TimeUtils.millis2String(
                                    TimeUtils.string2Date(list1.get(i).getCL_TIME()).getTime(), "yyyy-MM-dd"));
                        } catch (Exception e) {
                            e.printStackTrace();
                            xDayData.add(list1.get(i).getCL_TIME() +"");
                        }
                        yDayData.add(list1.get(i).getCL_VALUE().replace("μmol/L",""));
                    }
                }
                Collections.reverse(xDayData);
                Collections.reverse(yDayData);
                setChartData(xDayData, yDayData,0);
                lineChart.invalidate();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

//        xDayData.add("2020-12-15");
//        xDayData.add("2020-12-16");
//        xDayData.add("2020-12-17");
//        xDayData.add("2020-12-18");
//        xDayData.add("2020-12-19");
//        xDayData.add("2020-12-20");
//        xDayData.add("2020-12-21");
//        yDayData.add("2.1");
//        yDayData.add("2.5");
//        yDayData.add("2.8");
//        yDayData.add("1.1");
//        yDayData.add("2.0");
//        yDayData.add("3.1");
//        yDayData.add("4.5");
//
//        setChartData(xDayData, yDayData,0);
//        lineChart.invalidate();
    }

    /**
     * 为折线图设置数据，并且第一个图表的标签是日实时功率，后面的都是发电量，
     * 通过flag来判断,flag 0 实时功率 ，1  发电量
     * @param xData
     * @param yData
     * @param flag
     */
    private void setChartData(final List<String> xData , List<String> yData, int flag) {

        lineChart.getXAxis().setValueFormatter(new IAxisValueFormatter() {
            @Override
            public String getFormattedValue(float value, AxisBase axis) {
                int intValue = (int)value;
                if(xData.size()>intValue && intValue>=0){
                    //这样显示在X轴上值就是 05:30  05:35，不然会是1.0  2.0
                    return xData.get(intValue);
                }else{
                    return "";
                }
            }
        });
//        lineChart.getXAxis().setValueFormatter(new ValueFormatter() {
//            @Override
//            public String getAxisLabel(float value, AxisBase axis) {
//                int intValue = (int)value;
//                if(xData.size()>intValue && intValue>=0){
//                    //这样显示在X轴上值就是 05:30  05:35，不然会是1.0  2.0
//                    return xData.get(intValue);
//                }else{
//                    return "";
//                }
//            }
//        });
        lineChart.invalidate();

        MyMarkerView mv = new MyMarkerView(getActivity(), R.layout.custom_marker_view,xData);
        mv.setChartView(lineChart);
        lineChart.setMarker(mv);

        final ArrayList<Entry> values = new ArrayList<>();

        for (int i = 0; i < yData.size(); i++) {
            //注意这里的Entry（不一定需要）采用这种方式构造，采用其他的结果是一样的
            float y;
            try {
                y = Float.valueOf(yData.get(i));
            } catch (NumberFormatException e) {
                e.printStackTrace();
                y = 0;
            }
            values.add(new Entry(i, y,xData.get(i)));
        }

        LineDataSet lineDataset ;

        if (lineChart.getData() != null && lineChart.getData().getDataSetCount() > 0) {

            lineDataset = (LineDataSet) lineChart.getData().getDataSetByIndex(0);
            lineDataset.setDrawFilled(true);
            lineDataset.setFillDrawable(getResources().getDrawable(R.drawable.shape_line_gradiend_chart));
            lineDataset.setValues(values);
            if(flag==0){
                lineDataset.setLabel("尿酸(μmol/L)");
                lineDataset.setDrawFilled(true);
            }
            else{
                lineDataset.setLabel("尿酸(μmol/L)");
                lineDataset.setDrawFilled(false);
            }

            lineChart.getData().notifyDataChanged();
            lineChart.notifyDataSetChanged();

        }else{
            if(flag==0){
                lineDataset = new LineDataSet(values, "尿酸(μmol/L)");
                lineDataset.setDrawFilled(true);
            }else{
                lineDataset = new LineDataSet(values, "尿酸(μmol/L)");
                lineDataset.setDrawFilled(false);
            }

            lineDataset.setDrawFilled(true);
            lineDataset.setFillDrawable(getResources().getDrawable(R.drawable.shape_line_gradiend_chart));

            lineDataset.setColor(this.getResources().getColor(R.color.homecolor));

            //设置是否显示圆点
            lineDataset.setDrawCircles(true);
            lineDataset.setValueTextColor(this.getResources().getColor(R.color.homecolor));
            lineDataset.setColor(this.getResources().getColor(R.color.homecolor));
            lineDataset.setCircleColor(this.getResources().getColor(R.color.homecolor));
            lineDataset.setValueTextSize(10f);
            //是否显示每个点的Y值
            lineDataset.setDrawValues(true);

            LineData lineData = new LineData(lineDataset);
            lineChart.setData(lineData);
            lineChart.animateX(1000);

            //y轴显示整数
//            lineDataset.setValueFormatter(new ValueFormatter() {
//                @Override
//                public String getFormattedValue(float v) {
//                    String str = v + "";
//                    if (str.length()==0) {
//                        return str;
//                    }
//                    return str.substring(0, str.indexOf("."));//设置自己的返回位数
//                }
//            });

        }
    }

    private void initChartView() {
        //在点击高亮值时回调
        lineChart.setOnChartValueSelectedListener(this);

        //设置整个图表的颜色
        lineChart.setBackgroundResource(R.drawable.bg_line_chart);

        Legend l = lineChart.getLegend();
        l.setVerticalAlignment(Legend.LegendVerticalAlignment.TOP);
        l.setHorizontalAlignment(Legend.LegendHorizontalAlignment.LEFT);
        l.setOrientation(Legend.LegendOrientation.HORIZONTAL);
        l.setDrawInside(false);

        Description description = lineChart.getDescription();
        description.setYOffset(10);
        description.setEnabled(true);
        description.setText("时间");

        //是否可以缩放、移动、触摸
        lineChart.setTouchEnabled(true);
        lineChart.setDragEnabled(true);

        //不能让缩放，不然有bug，所以接口也没实现
        lineChart.setScaleEnabled(false);
        lineChart.setPinchZoom(true);

        //设置图表距离上下左右的距离
        lineChart.setExtraOffsets(10, 10, 10, 0);

        //获取左侧侧坐标轴
        YAxis leftAxis = lineChart.getAxisLeft();

        //设置是否显示Y轴的值
        leftAxis.setDrawLabels(true);
        leftAxis.setTextColor(this.getResources().getColor(R.color.color_8f8f));

        //设置所有垂直Y轴的的网格线是否显示
        leftAxis.setDrawGridLines(true);

        //设置虚线
        leftAxis.enableGridDashedLine(10f, 10f, 0f);
        leftAxis.setDrawZeroLine(false);

        //设置Y轴最大值最小值，如果不设置取数据里面的值，如果设置则按照设置的值
//        leftAxis.setAxisMinimum(12f);
//        leftAxis.setAxisMinimum(0f);
//        leftAxis.setAxisMaxValue(11f);
//        leftAxis.setAxisMinValue(0f);

        //将右边那条线隐藏
        lineChart.getAxisRight().setEnabled(false);
        //获取X轴
        XAxis xAxis = lineChart.getXAxis();
        //设置X轴的位置，可上可下
        xAxis.setPosition(XAxis.XAxisPosition.BOTTOM);
        //设置x轴间距
        xAxis.setGranularity(0.9f);

        //将垂直于X轴的网格线隐藏，将X轴显示
        xAxis.setDrawGridLines(false);
        xAxis.setDrawAxisLine(true);

        //设置X轴上lable颜色和大小
        xAxis.setTextSize(8f);
        xAxis.setTextColor(Color.GRAY);

        //设置X轴高度
        xAxis.setAxisLineWidth(1);
    }

    @Override
    public void onValueSelected(Entry e, Highlight h) {

    }

    @Override
    public void onNothingSelected() {

    }

}
